package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.BadreplyMapper;
import com.indusfo.spc.mapper.BadreplyTypeMapper;
import com.indusfo.spc.pojo.Badreply;
import com.indusfo.spc.pojo.BadreplyType;
import com.indusfo.spc.service.BadreplyTypeService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XCommonUtil;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class BadreplyTypeServiceImpl implements BadreplyTypeService {

    private  static  final Logger logger = LoggerFactory.getLogger(BadreplyServiceImpl.class);

    @Autowired
    private BadreplyTypeMapper badreplyTypeMapper;

    @Autowired
    private BadreplyMapper badreplyMapper;

    /**
     * 更新不良对策类
     *
     * @param badreplyType
     * @return JSONObject
     */
    @Override
    public JSONObject updateBadreplyType(BadreplyType badreplyType) {
        String remark = badreplyType.getRemark();
        if(remark == null) {
            remark = "";
        }
        if(badreplyType.getBadreplyTypePid()==null){
            badreplyType.setBadreplyTypePid(0);
        }
        try {
            if(badreplyType.getBadreplyTypeId() == null) {
                throw new ParamsErrorException("请选择要编辑的不良对策类");
            }
            checkParam(badreplyType, remark);
            // 调用存储过程
            int row = badreplyTypeMapper.updateBadreplyType(badreplyType);
            if(row == 0) {
                throw new ModifyFailedException("数据编辑失败");
            }
            return JSONObject.oK("编辑成功");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 获取不良对策类树
     *
     * @param badreplyType
     * @return JSONObject
     */
    @Override
    public JSONObject detpsTree(BadreplyType badreplyType) {
        List<XTreeNode> tree = null;
        try {
            tree = new ArrayList<>();
            List<XTreeNode> nodes = new ArrayList<>();
            List<BadreplyType> list = badreplyTypeMapper.AllBadreplyType(badreplyType);
            // 树中加入全部
            if(badreplyType.getFlag()!=null) {
                BadreplyType badreplyType1 = new BadreplyType();
                badreplyType1.setBadreplyTypeId(0);
                badreplyType1.setBadreplyTypePid(0);
                badreplyType1.setBadreplyTypeName("全部");
                list.add(0, badreplyType1);
                //生成树list
                if (null != list) {
                    List<XTreeNode> treelist = new ArrayList<>();
                    for (BadreplyType _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getBadreplyTypeId());
                        node.setpId(_MouldType.getBadreplyTypePid());
                        node.setTitle(_MouldType.getBadreplyTypeName());
                        treelist.add(node);
                    }
                    XTreeUtil xTreeUtil = new XTreeUtil(badreplyType.getFlag(), treelist);
                    List<Integer> childs = new ArrayList<>();
                    List<Integer> parents = new ArrayList<>();
                    childs = xTreeUtil.getChilds();
                    parents = xTreeUtil.getParents();
                    if (null != list) {
                        for (BadreplyType _MouldType : list) {
                            XTreeNode node = new XTreeNode();
                            node.setId(_MouldType.getBadreplyTypeId());
                            node.setpId(_MouldType.getBadreplyTypePid() == 0 ? null : _MouldType.getBadreplyTypePid());
                            if (parents.contains(_MouldType.getBadreplyTypeId())) {
                                node.setExpand(true);
                            }
                            if (!badreplyType.getFlag().equals(0)) {
                                if (badreplyType.getFlag().equals(_MouldType.getBadreplyTypeId())) {
                                    node.setSelected(true);
                                }
                            }
                            node.setTitle(_MouldType.getBadreplyTypeName());
                            nodes.add(node);
                        }
                    }
                }
                tree = XCommonUtil.getTree(nodes, null);
                if(badreplyType.getFlag().equals(0)){
                    tree.get(0).setSelected(true);
                }
            }else {
                if (null != list) {
                    for (BadreplyType _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getBadreplyTypeId());
                        node.setpId(_MouldType.getBadreplyTypePid() == 0 ? null : _MouldType.getBadreplyTypePid());
                        node.setTitle(_MouldType.getBadreplyTypeName());
                        nodes.add(node);
                    }
                }
                tree = XCommonUtil.getTree(nodes, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.oK(tree);
    }
    /**
     * 添加不良对策类
     *
     * @param badreplyType
     * @return JSONObject
     */
    @Override
    public JSONObject insertBadreplyType(BadreplyType badreplyType) {
        badreplyType.setDataState(1);
        String remark = badreplyType.getRemark();
        if(remark == null) {
            remark = "";
        }
        try {
            if(badreplyType.getBadreplyTypeId() != null) {
                throw new ParamsErrorException("新增不良对策时，不能填写id");
            }
            if(badreplyType.getBadreplyTypePid()==null){
                badreplyType.setBadreplyTypePid(0);
            }
            checkParam(badreplyType, remark);

            int row = badreplyTypeMapper.insertBadreplyType(badreplyType);

            if(row == 0) {
                throw new ModifyFailedException("数据新增失败");
            }
            return JSONObject.oK("新增成功",badreplyType.getBadreplyTypeId());
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject queryBadreplyType(BadreplyType badreplyType) {
        return null;
    }

    /**
     * 删除不良对策类
     *
     * @param badreplyTypeIds
     * @return JSONObject
     */
    // 开启事务
    @Transactional
    @Override
    public JSONObject deleteBadreplyType(Long[] badreplyTypeIds){
        try {
            if (badreplyTypeIds == null) {
                throw new ParamsErrorException("不良对策类id不能为空");
            }
            String msg = "";
            for(Long badreplyTypeId:badreplyTypeIds){
                // 判断是否有子集
                BadreplyType badreplyType  = new BadreplyType();
                badreplyType.setBadreplyTypePid(badreplyTypeId.intValue());
                List<BadreplyType> badreplyTypeList = badreplyTypeMapper.AllBadreplyType(badreplyType);
                if(badreplyTypeList.size()!=0){
                    throw new ParamsErrorException("该不良对策类下还有子集");
                }
                // 判断下面是否有不良对策
                Badreply badreply  = new Badreply();
                badreply.setBadreplyTypeId(badreplyTypeId.intValue());
                List<Badreply> badreplies = badreplyMapper.selectAll(badreply);
                if(badreplies.size()>0){
                    throw new ParamsErrorException("该不良对策类下还有不良对策");
                }
                // 执行删除
                int row = badreplyTypeMapper.deleteBadreplyType(badreplyTypeIds);
                if (row == 0) {
                    new ModifyFailedException("删除失败");
                } else {
                    msg = "删除成功";
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /**
     * 参数校验
     *
     * @param badreplyType
     * @param vcRemark
     */
    private void checkParam(BadreplyType badreplyType, String vcRemark) {
        if (badreplyType.getBadreplyTypePid() == null) {
            throw new ParamsErrorException("不良对策类型不能为空");
        }
        if (StringUtils.isEmpty(badreplyType.getBadreplyTypeName())) {
            throw new ParamsErrorException("请填写不良对策类型名称");
        }
        if (("全部").equals(badreplyType.getBadreplyTypeName())) {
            throw new ParamsErrorException("该不良对策类型名称已存在");
        }
        if (badreplyType.getBadreplyTypeName().getBytes().length > 50) {
            throw new ParamsErrorException("名称超过规定长度");
        }
        if (vcRemark.getBytes().length > 100) {
            throw new ParamsErrorException("说明字数超过规定长度");
        }
        // 名称不能重复
        Integer depCounts = badreplyTypeMapper.selectBadreplyTypeName(badreplyType);
        if (depCounts !=0) {
            throw new ParamsErrorException("该不良对策类型已存在");
        }
    }
}
